import axios from 'axios';
import { getUserInfo } from '@/data/common.js';
import { Message } from 'element-ui';

// 处理嵌套异步问题
const toFnu = fun => {
  return fun.then(res => {
    return [null, res];
  }).catch(err => [err])
}

const path = process.env.NODE_ENV === 'development' ? '/api' : '';

const service = axios.create({
  timeout: 10000
});
service.interceptors.request.use(config => {
  let isLoginObj = getUserInfo(), Authorization = {};
  if(isLoginObj.isLogin === true){
    Authorization = {
      'x-jwt-token': isLoginObj.token
    }
  }
  config.headers = {
    'Content-Type': 'application/json',
    ...Authorization
  }
  return config;
}, error => {
    Promise.reject(error);
});

service.interceptors.response.use(res => { 
  if(res.data.code === 401){
    Message({
      showClose: true,
      message: res.data.msg,
      type: 'error'
    });
    localStorage.removeItem('token');
    window.location.href = window.location.origin;
    return false;
  }
  if(res.data.code === "100"){
    return res.data;
  }else{
    Message({
      showClose: true,
      message: res.data.msg,
      type: 'error'
    });
    return false;
  }
}, error => {
  // 状态码
  if(error.response.status === 401){
    localStorage.removeItem('token');
    Message({
      showClose: true,
      message: '登录超时',
      type: 'error'
    });
    window.location.href = window.location.origin;
  }else{
    Message({
      showClose: true,
      message: '系统繁忙，请稍后再试',
      type: 'error'
    });
  }
  console.error(error);
  return Promise.reject(error);
});

export { service, toFnu, path };